import React, { Component } from 'react';
import { getList } from './api'
import './App.css'
import ListItem from './components/ListItem'
class App extends Component {
  state = {
    list: []
  }
  async getListAndSet() {
    const resp = await getList()
    console.log(resp.data);
    this.setState({
      list: resp.data.data
    })
  }
  handleDone = (id) => {
    const { list } = this.state;
    // 精确查找数据
    const item = list.find(item => item.id === id)
    item.isDone = true
    this.setState({
      list: [...list]
    })
  } 
  handleDelete = (id) => {
    const { list } = this.state;
    // 过滤id
    const newList = list.filter(item => item.id !== id)
    this.setState({
      list: newList
    })
  }
  handleAdd() {
    const { list } = this.state

    list.push({
      id: new Date().getTime().toString(),
      title: this.ipt.value,
      isDone: false,
      datetime: new Date().toLocaleString()
    })

    this.ipt.value = ''

    this.setState({
      list: [...list]
    })
  }
  handleKeyDown(e) {
    if(e.keyCode === 13) {
      this.handleAdd()
    }
  }
  componentDidMount() {
    this.getListAndSet()
  }
  render() {
    const { list } = this.state
    return (
      <div className="container">
        <div className="header">
          {/* 获取节点  通过  ref={ ref => this.名字 = ref } */}
          <input type="text" ref={ ref => this.ipt = ref } onKeyDown={ (e) => this.handleKeyDown(e) }/>
          <button onClick={ () => this.handleAdd() }>添加</button>
        </div>
        <div className="list">
          <ul>
            {
              list.length > 0 && list.map(v => {
                return (
                  <ListItem key={v.id} { ...v } 
                    handleDelete={ this.handleDelete }
                    handleDone={ this.handleDone }
                  ></ListItem>
                )
              })
            }
          </ul>
        </div>
      </div>
    );
  }
}

export default App;
